package com.chaos.auth.service.feign;


import com.chaos.auth.api.feign.Oauth2Feign;
import com.chaos.auth.entity.SelfOauth2RegisteredClient;
import com.chaos.auth.mapper.Oauth2RegisteredClientMapper;
import com.chaos.framework.model.dto.result.data.DataResult;
import com.chaos.framework.starter.base.BaseController;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * @author jacky
 * @since 2025-04-21
 */
@RestController
@AllArgsConstructor
@RequestMapping(value = {"/oauth2RegisteredClient"})
@Tag(name = "", description = "")
@Hidden
public class Oauth2RegisteredClientController extends BaseController implements Oauth2Feign {


    private final Oauth2RegisteredClientMapper oauth2RegisteredClientMapper;

    @Override
    @PostMapping("/add")
    public DataResult add() {
        SelfOauth2RegisteredClient client = new SelfOauth2RegisteredClient();
        client.setId(UUID.randomUUID().toString());
        client.setClientId("oidc-client");
        client.setClientSecret("{noop}secret");
        client.setClientName("oidc-client");
        Set<ClientAuthenticationMethod> methodSet = new HashSet<>();
        client.setClientAuthenticationMethods(new HashSet<>(Collections.singleton(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue())));
        Set<String> typeSet = new HashSet<>();
        typeSet.add(AuthorizationGrantType.AUTHORIZATION_CODE.getValue());
        typeSet.add(AuthorizationGrantType.REFRESH_TOKEN.getValue());
        client.setAuthorizationGrantTypes(typeSet);
        client.setRedirectUris(new HashSet<>(Collections.singleton("http://localhost:8080/login/oauth2/code/oidc" +
                "-client")));
        client.setPostLogoutRedirectUris(new HashSet<>(Collections.singleton("http://localhost:8080/")));
        Set<String> scopeSet = new HashSet<>();
        scopeSet.add(OidcScopes.OPENID);
        scopeSet.add(OidcScopes.PROFILE);
        client.setScopes(scopeSet);
        client.setClientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build());
        client.setTokenSettings(TokenSettings.builder().build());

        oauth2RegisteredClientMapper.insert(client);
        System.out.println(client);
        return null;
    }


}
